#include <iostream>
#include <typeinfo>
#include <assert.h>
class any
{
private:
    class holder
    {
    public:
        virtual const std::type_info &type() = 0; // 获取子类保存的数据类型
        virtual holder *clone() = 0;              // 针对当前对象自身，clone出新的子类对象
        virtual ~holder() {};
    };
    template <typename T>
    class placeholder : public holder
    {
    public:
        placeholder(const T &val) : _val(val) {}
        virtual const std::type_info &type() { return typeid(T); }    // 获取子类保存的数据类型
        virtual holder *clone() { return new placeholder<T>(_val); }; // 针对当前对象自身，clone出新的子类对象;
    public:
        T _val;
    };
    holder *_content;

public:
    any() : _content(NULL) {}
    template <class T>
    any(const T &val) : _content(new placeholder<T>(val)) {}
    any(const any &other) : _content(other._content ? other._content->clone() : NULL) {}
    ~any() { delete _content; }

    template <typename T>
    T *get()
    {
        assert(typeid(T) == _content->type());
        return &((placeholder<T> *)_content)->_val;
    };

    any &swap(any &other)
    {
        std::swap(_content, other._content);
        return *this;
    }
    template <typename T>
    // 赋值重载
    any &operator=(const T &val)
    {
        // 为当前val构造any对象并做交换,此时原先指针被交换到临时变量里面，当对象释放的时候指针也被释放
        any(val).swap(*this);
        return *this;
    };
    any &operator=(const any &other)
    {
        any(other).swap(*this);
        return *this;
    };
};

int main()
{
    any a;
    a = 10;
    int *pa = a.get<int>();
    std::cout << *pa;
    return 0;
}